﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.ApproveCommand;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Transactions;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.ApproveCommandHandler
{
    /// <summary>
    /// 添加审批记录表-命令执行
    /// </summary>
    public class AddLeaveRecordModelCommandHandler : IRequestHandler<AddLeaveRecordModelCommand, APIResult<string>>
    {
        private readonly IBaseRepository<LeaveRecordModel> leaveRecordRepos;
        private readonly IBaseRepository<LeaveModel> leaveRepos;
        private readonly IBaseRepository<User> userRepos;
        private readonly IMapper mapper;

        public AddLeaveRecordModelCommandHandler(
            IBaseRepository<LeaveRecordModel> leaveRecordRepos,
            IBaseRepository<LeaveModel> leaveRepos,
            IBaseRepository<User> userRepos,
            IMapper mapper)
        {
            this.leaveRecordRepos = leaveRecordRepos;
            this.leaveRepos = leaveRepos;
            this.userRepos = userRepos;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加审批记录表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<string>> Handle(AddLeaveRecordModelCommand request, CancellationToken cancellationToken)
        {
            APIResult<string> result = new APIResult<string>();


            //事物 TransactionScopeAsyncFlowOption.Enabled
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                //添加LeaveRecordModel审批记录
                LeaveRecordModel leaveRecord = new LeaveRecordModel();
                leaveRecord.LeaveId = request.LeaveId;
                leaveRecord.DepId = request.DepId;
                leaveRecord.UserId = request.UserId;
                leaveRecord.ApproveNickName = request.ApproveNickName;
                leaveRecord.RecordStatus = request.RecordStatus;
                leaveRecord.LevelRoleId = request.LevelRoleId;
                leaveRecord.CreateTime = request.CreateTime.AddHours(8);
                leaveRecord.Reason = request.Reason;
                int res = await leaveRecordRepos.Add(leaveRecord);

                //查询记录表  获取当前审批级别 已审批人数 每个 的状态(通过 或 不通过) 
                var Recordlist = leaveRecordRepos.GetAll().Result.Where(x => x.DepId == request.DepId && x.LevelRoleId == request.LevelRoleId && x.LeaveId == request.LeaveId).ToList();
                //记录条数
                int RecordNum = Recordlist.Count();
                //并且通过的数量 1--通过 
                int RecordStatusNum = Recordlist.Where(x => x.RecordStatus == "通过").ToList().Count();
                //查询审批人UserModel
                var UserList = userRepos.GetAll().Result.Where(x => x.DepId == request.DepId && x.LevelRoleId == request.LevelRoleId).ToList();
                //审批人数量
                int UserNum = UserList.Count();

                //最后一层 当全部通过 修改请假申请审核状态 为已通过
                if (RecordNum == UserNum && RecordNum == RecordStatusNum && request.LevelRoleId == 2) // 记录条数 == 审批人数量 && 通过数量 == 记录条数 && 审批级别 == 2(最高审批人)  ==> 修改LeaveId 请假申请表状态 == 已通过
                {
                    var LeaveModel = await leaveRepos.GetAll().Result.FirstOrDefaultAsync(x => x.LeaveId == request.LeaveId);
                    LeaveModel.AppStatus = 2;
                    LeaveModel.LevelRoleId = LeaveModel.LevelRoleId - 1;
                    //修改状态
                    await leaveRepos.Update(LeaveModel);
                }

                //中间层 当全部审批完 && 全为通过 ==> 修改审批层数-1 --审送
                if (RecordNum == UserNum && RecordNum == RecordStatusNum && request.LevelRoleId != 2) //// 记录条数 == 审批人数量 && 通过数量 == 记录条数 && 审批级别 != 2(最高审批人)  ==> 修改LeaveId 请假申请表审批级数 == -1
                {
                    var LeaveModel = await leaveRepos.GetAll().Result.FirstOrDefaultAsync(x => x.LeaveId == request.LeaveId);
                    LeaveModel.LevelRoleId = LeaveModel.LevelRoleId - 1;
                    //修改审批级数
                    await leaveRepos.Update(LeaveModel);
                }

                //当任何步骤 为不通过 修改请假申请状态 为 3 (不通过) 
                if (request.RecordStatus == "不通过") //request.RecordStatus == 2(不通过) ==> 修改LeaveId 请假申请表状态 = 未通过
                {
                    var LeaveModel = await leaveRepos.GetAll().Result.FirstOrDefaultAsync(x => x.LeaveId == request.LeaveId);
                    LeaveModel.Reason = request.Reason;
                    LeaveModel.AppStatus = 3;
                    //修改状态
                    await leaveRepos.Update(LeaveModel);
                }
                result.Code = APIEnum.审批完成;
                result.Msg = APIEnum.审批完成.ToString();
                result.data = res.ToString();
                //提交事物
                tran.Complete();
            }            
            return await Task.FromResult(result);
        }
    }
}
